package com.tyler.voice;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Component
@ServerEndpoint(value = "/ws/a")
public class WebSocketServer {
    private static final ConcurrentHashMap<String, Session> aSessions = new ConcurrentHashMap<>();
    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private WebSocketClient cClient = new WebSocketClient("ws://localhost:8082/ws/c");

    @OnOpen
    public void onOpen(Session session) {
        String sessionId = session.getId();
        aSessions.put(sessionId, session);
        System.out.println("A项目连接已建立，SessionID: " + sessionId);
        cClient.connect(); // 连接 C 项目
    }

    @OnMessage
    public void onMessage(Session session, String controlMsg) {
        System.out.println("收到控制消息：" + controlMsg);
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("text", "----------------已经收到数据了。。。。。。。。。。。。。。。");
            session.getBasicRemote().sendText(JSON.toJSONString(jsonObject));
        } catch (IOException e) {
            System.out.println("发送数据到A项目失败");
        }
        cClient.sendText(controlMsg);
    }

    @OnMessage
    public void onMessage(Session session, byte[] audioData) {
        System.out.println("收到A项目语音数据，长度：" + audioData.length + " bytes");
        try {
            JSONObject jsonObject = new JSONObject();
            Random random = new Random();
            jsonObject.put("text", random.nextInt(10, 100));
            session.getBasicRemote().sendText(JSON.toJSONString(jsonObject));
        } catch (IOException e) {
            System.out.println("发送数据到A项目失败");
        }
        cClient.send(audioData);
    }

    @OnClose
    public void onClose(Session session) {
        String sessionId = session.getId();
        scheduler.schedule(() -> {
            cClient.disconnect();
            aSessions.remove(sessionId);
            System.out.println("A项目连接已关闭，SessionID: " + sessionId);
        }, 500, TimeUnit.MICROSECONDS);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        // 忽略因连接关闭导致的 IOException （关键）
        if (!(error instanceof IOException && error.getMessage() != null && error.getMessage().contains("中止了一个已建立的连接"))) {
            System.out.println("A项目连接异常："+error.getMessage());
        }
    }

}
